package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.mybatis.service.impl.CoolServiceImpl;
import cn.da.shuai.cool.system.service.mapper.CoolRoleMapper;
import cn.da.shuai.cool.system.model.entity.role.CoolRole;
import cn.da.shuai.cool.system.model.entity.role.SearchRoleVo;
import cn.da.shuai.cool.system.model.entity.role.UpdateRoleVo;
import cn.da.shuai.cool.system.service.service.ICoolPermissionService;
import cn.da.shuai.cool.system.service.service.ICoolRoleService;
import cn.da.shuai.cool.system.service.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CoolRoleServiceImpl extends CoolServiceImpl<CoolRoleMapper, CoolRole> implements ICoolRoleService {

    private final ICoolPermissionService permissionService;

    public CoolRoleServiceImpl(ICoolPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(UpdateRoleVo updateRoleVo) {
        CoolRole role = new CoolRole();
        BeanUtils.copyProperties(updateRoleVo, role);
        role.setUpdateBy(UserUtil.getUserId());
        save(role);
        if (updateRoleVo.getMenuIds() != null && !updateRoleVo.getMenuIds().isEmpty()) {
            permissionService.assignRoleMenus(role.getId(), updateRoleVo.getMenuIds());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(UpdateRoleVo updateRoleVo) {
        if (updateRoleVo==null || updateRoleVo.getId() == null) {
            return;
        }
        CoolRole role = new CoolRole();
        BeanUtils.copyProperties(updateRoleVo, role);
        role.setUpdateBy(UserUtil.getUserId());
        updateById(role);
        if (updateRoleVo.getMenuIds() != null) {
            permissionService.assignRoleMenus(role.getId(), updateRoleVo.getMenuIds());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRole(Integer id) {
        removeById(id);
        // 删除角色菜单关联
        permissionService.assignRoleMenus(id, null);
    }

    @Override
    public List<CoolRole> listAllRoles() {
        return list();
    }

    @Override
    public List<CoolRole> getRoleByUserId(Integer userId) {
        if (userId == null) {
            return List.of();
        }
        return this.baseMapper.selectRoleByUserId(userId);
    }
}